import React, { useState } from "react";
import defaultImaage from "../../../../img/defaultImg.gif";
import { Service } from "@/lib";
import { Button, Image } from "antd";
import FileManage from "../../Component/FileManage";
import { UploadOutlined } from "@ant-design/icons";

interface IFileManageProps {
    value?: string;
    filterType?: "image"|"video"| "audio" | "pdf";
    onChange?: (value: string) => void;
    hidePreview?: boolean;
    placeholder?: string;
    validate?: (file: File) => boolean;
    btnText?: string;
    description?: string|React.ReactNode;
}
export const Cover = ({ value, onChange, hidePreview, placeholder, validate, filterType, btnText, description }: IFileManageProps) => {
    const serviceApi = Service.useService();
    const [ source, setSource ] = useState<any>({});
    const [ imgPref ] = useState(() => serviceApi.getUrl("resource.mediaUrl"));
    const [ imgUrl, setImgUrl ] = useState(() => {
        return value ? imgPref + "/" + value : defaultImaage;
    });
    const [ showFileManage, setShowFileManage ] = useState(false);
    return (
        <div>
            <Button style={{ display: "block", marginBottom: 5 }}
                onClick={() => setShowFileManage(true)}
                icon={<UploadOutlined />}
            >
                { btnText || "选择图片" }
            </Button>
            { placeholder && <>{placeholder}</> }
            { !hidePreview && (filterType === "image" || !filterType) && <Image src={imgUrl} style={{ display: "block", maxWidth: 80 }}/> }
            { filterType !== "image" && filterType && <label>{source?.name}</label> }
            { showFileManage && <FileManage
                defaultSelected={value ? [value] : []}
                filterType={filterType || "image"}
                validate={validate}
                onConfirm={(fileList, sourceList) => {
                    const fileId = fileList[0];
                    const value = !filterType || filterType === "image" ? fileId : sourceList[0];
                    setImgUrl(imgPref + "/" + fileId);
                    setSource(sourceList[0]);
                    typeof onChange === "function" && onChange(value);
                    setShowFileManage(false);
                }}
                onCancel={() => {
                    setShowFileManage(false);
                }}
            /> }
            { description && <>{description}</> }
        </div>
    );
};